<template>
  <div>
    <el-button type="primary" @click="getLabelName();dialogFormVisible = true" size="small">编辑</el-button>

    <el-dialog title="添加标签" :visible.sync="dialogFormVisible" v-bind:before-close="open" width="30%">
      <el-form ref="addLabel" :model="form" v-bind:rules="rules">
        <el-form-item label="标签名" :label-width="formLabelWidth" prop="label">
          <el-input v-model="form.label" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false" v-on:click="onSubmit('addLabel')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import qs from "qs";

export default {
  inject:['reload'],
  name: "LabelUpdate",
  props:['labelName','lid'],
  data(){
    let labelNameValidate=(rule,value,callback)=>{
      this.axios.post('/blog/checkLabelExist',qs.stringify({
        label:this.form.label,
      })).then((response)=>{
        if (response.data.status===6){
          callback(new Error('此标签已存在'));
        }else {
          callback();
        }
      })
    };
    return{
      dialogFormVisible:false,
      formLabelWidth:'100px',
      form:{
        label:'',
      },
      rules:{
        label:[
          {required:true, message:'内容不能为空', trigger:'blur'},
          {validator:labelNameValidate,trigger: 'blur'}],
      }
    }
  },
  methods:{
    onSubmit(formName){
      this.$refs[formName].validate((valid)=>{
        if (valid){
          this.axios.post('/blog/updateLabel',qs.stringify({
            labelName:this.form.label,
            lid:this.lid,
          })).then((response)=>{
            this.$message.success(response.data.tip);
            this.reload();
          });
        }else {
          this.$message.error("输入内容无效，请正确填写");
        }
      });
    },
    open() {
      this.$confirm('内容尚未提交，是否退出?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dialogFormVisible=false;
      }).catch(() => {
      });
    },
    getLabelName(){
      this.form.label = this.labelName;
    }
  }
}
</script>

<style scoped>

</style>
